# 佐糖平台接口sdk
from ratelimit import sleep_and_retry, limits
import requests

from app.dependencies import singleton
from app.utils.index import base2bytes


# 佐糖接口实例
@singleton
class ZuoTangClient:
    def __init__(self):
      self.__api_key = "wx8fccy9jxjja5fw5"

    # 人像分割
    @sleep_and_retry            # 等待放行
    @limits(calls=9, period=1) # 最多每秒10次
    def body_seg(self, bs64: str, bg_color: str="#00A3E6") -> bytes:
      files = {
        "image_file": base2bytes(bs64)
      }
      options = {
        "sync": "1",        # 同步
        "type": "person",   # 使用人作为前景
        # "return_type": "2", # 以base64字符串形式返回图片
        "return_type": "3", # 以二进制流的形式返回图片
        "output_type": "2", # 只返回前景图片
        "crop": "0",        # 返回原始图像大小
        "format": "jpg",
        "bg_color": bg_color.split('#')[-1],
      }

      url = "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
      headers = {'X-API-KEY': self.__api_key}
      response = requests.post(url, files=files, data=options, headers=headers)
      if response.status_code != 200:
        raise Exception(f"[{response.status_code}]{response.text}")

      content_type = response.headers.get("Content-Type")
      if content_type != "application/json":
        return response.content   # 返回文件流
      else:
        json = response.json()
        if "status" not in json or json["status"] != 200:
          status_code = json.get("status")
          message = json.get("message")
          raise Exception(f"抠图接口异常:[{status_code}] {message}")
        else:
          data = json.get("data")
          message = data.get("err_message")
          raise Exception(f"抠图接口异常:{message}")

      # json = response.json()
      # if "status" not in json or json["status"] != 200:
      #   status_code = json.get("status")
      #   raise Exception(f"request error[{status_code}]")
      #
      # data = json.get("data")
      # if "state" not in data:
      #   raise Exception("response data state is empty")
      # state_code = data.get("state")
      # if state_code != 1:
      #   state_detail = data.get("state_detail")
      #   err_message = data.get("err_message")
      #   raise Exception(f"[{state_code}]{state_detail}: {err_message}")
      #
      # if "image" not in data or not data.get("image"):
      #   raise Exception(f"response data image is empty")
      #
      # return data.get("image")
